﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.CompilerServices;

namespace SAM.Framework.BasicExtends
{
    /// <summary>
    /// 可实例化类型的扩展
    /// </summary>
    public static class ClassExtends
    {
        /// <summary>
        /// 扩展class对象的深度复制，class必须要是可以实例化的
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="source">实体</param>
        /// <returns></returns>
        public static T DeepClone<T>(this T source) where T : class
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be Serializeable", "source");
            }
            if (Object.ReferenceEquals(source, null))
            {
                return default(T);
            }
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }
    }
}
